package com.itheima.web;

import com.itheima.dto.SetmealDto;
import com.itheima.pojo.Setmeal;
import com.itheima.service.CheckGroupService;
import com.itheima.service.SetmealService;
import com.itheima.support.Result;
import com.itheima.utils.RedisUtil;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/setmeal")
public class SetmealController {

    @DubboReference
    private SetmealService setmealService;

    @DubboReference
    private CheckGroupService checkGroupService;

    //查看所有套餐
    @GetMapping("/findAll")
    public Result<List<Setmeal>> findAll() {
        //先从redis中获取数据，若数据不为空，则直接返回数据，若为空，则查询数据库
        //并将数据库中的数据存放到redis中
        List<Setmeal> setmealList = RedisUtil.findAllOfHash("setmeal_hash");
        if (!ObjectUtils.isEmpty(setmealList)) {
            return Result.build(setmealList);
        }
        setmealService.list().stream().forEach(setmeal -> {
            RedisUtil.putToHash("setmeal_hash", String.valueOf(setmeal.getId()), setmeal);
        });
        return Result.build(setmealService.list());
    }

    //套餐详细信息
    @GetMapping("/detail/{setmealId}")
    public Result<SetmealDto> detail(@PathVariable("setmealId") Long setmealId) {
        //先从redis中获取值
        Setmeal setmeal = RedisUtil.getFromHash("setmeal_hash", String.valueOf(setmealId));
        //判断setmeal是否为空，若不为空，则直接返回，若为空，从数据库中查询
        if (!ObjectUtils.isEmpty(setmeal)) {
            SetmealDto setmealDto = new SetmealDto();
            BeanUtils.copyProperties(setmeal, setmealDto);
            setmealDto.setCheckGroups(checkGroupService.selectBySetmealId(setmealId));
            return Result.build(setmealDto);
        }
        return Result.build(setmealService.detail(setmealId));

    }

    @GetMapping("/info/{id}")
    public Result<Setmeal> info(@PathVariable("id") Long id) {
        Setmeal setmeal = RedisUtil.getFromHash("setmeal_hash", String.valueOf(id));
        if (!ObjectUtils.isEmpty(setmeal)) {
            return Result.build(setmeal);
        }
        return Result.build(setmealService.getById(id));
    }
}
